package com.ninetaildemonfox.zdl.socialproject.mvp.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.hyphenate.easeui.utils.Preferences;
import com.hyphenate.easeui.utils.map.JSONUtils;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;
import com.kongzue.baseokhttp.HttpRequest;
import com.kongzue.baseokhttp.listener.ResponseListener;
import com.kongzue.baseokhttp.util.Parameter;
import com.kongzue.dialog.interfaces.OnDialogButtonClickListener;
import com.kongzue.dialog.util.BaseDialog;
import com.kongzue.dialog.v3.MessageDialog;
import com.kongzue.dialog.v3.WaitDialog;
import com.kongzue.takephoto.TakePhotoUtil;
import com.ninetaildemonfox.zdl.ninetaildemonfox.base.BaseFragment;
import com.ninetaildemonfox.zdl.socialproject.R;
import com.ninetaildemonfox.zdl.socialproject.SpApplication;
import com.ninetaildemonfox.zdl.socialproject.base.BaseActivity;
import com.ninetaildemonfox.zdl.socialproject.mvp.contract.DHomeContract;
import com.ninetaildemonfox.zdl.socialproject.mvp.contract.DetaillnterfaceContract;
import com.ninetaildemonfox.zdl.socialproject.mvp.presenter.DHomePresenter;
import com.ninetaildemonfox.zdl.socialproject.mvp.presenter.DetaillnterfacePresenter;
import com.ninetaildemonfox.zdl.socialproject.mvp.ui.activity.AuthenticationCenterActivity;
import com.ninetaildemonfox.zdl.socialproject.mvp.ui.activity.DetailInterfaceActivity;
import com.ninetaildemonfox.zdl.socialproject.mvp.ui.activity.VipActivity;
import com.ninetaildemonfox.zdl.socialproject.mvp.ui.adapter.DHomeAdapter;
import com.ninetaildemonfox.zdl.socialproject.utils.ToastUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;
import java.util.Map;

import butterknife.BindView;

import static android.app.Activity.RESULT_OK;

/**
 * @author NineTailDemonFox
 * @date 2019/7/15 16:25
 * 功能描述：首页上面的  附近   新来  认证
 * 联系方式：1037438704@qq.com
 */
public class DHomeFragment extends BaseFragment implements DHomeContract, DetaillnterfaceContract {
    @BindView(R.id.recycerView)
    RecyclerView recycerView;
    private DHomeAdapter dHomeAdapter;
    private DHomePresenter dHomePresenter;
    public DetaillnterfacePresenter presenter;
    private String sex;
    public int type;
    public String city;
    public static int page = 1;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.frame_gone)
    FrameLayout frame_gone;
    private TextView text_error;

    public static String jingdu, weidu;
    ;

    @Subscribe
    @Override
    public void onInitView(Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        initView();
        initData();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void initData() {
        dHomeAdapter.setmOnClick(new DHomeAdapter.AdpItemOnClick() {
            @Override
            public void onClick(int position, Map<String, String> thisdata, int type) {
                if (type == 0) {
                    presenter.addMylike(token, thisdata.get("id"));
                    return;
                } else {
                    if (refreshLayout != null) {
                        refreshLayout.finishRefresh();
                        refreshLayout.finishLoadMore();
                    }
                    //判断是否进入
                    panduan(thisdata, position);
                }
            }
        });
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                http();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                http();
            }
        });
    }


    @Override
    public void onResume() {
        super.onResume();
    }

    public void http() {
        if (dHomePresenter == null) {
            dHomePresenter = new DHomePresenter(this, fgtContext);
        }
        if (token == null) {
            token = Preferences.getInstance().getString(me, "user", "token");
        }
        dHomePresenter.getIndex(token, sex,
                jingdu + "", weidu + "", page + "", type + "", city, "");
    }

    private View error;

    private void initView() {
        if (dHomePresenter == null) {
            dHomePresenter = new DHomePresenter(this, fgtContext);
        }
        presenter = new DetaillnterfacePresenter(fgtContext, this);
        recycerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        dHomeAdapter = new DHomeAdapter(getContext());
        dHomeAdapter.setJump(1);
        error = getLayoutInflater().inflate(R.layout.view_nomore, null);
        text_error = error.findViewById(R.id.text_error);
        dHomeAdapter.setNoMore(error);
        recycerView.setAdapter(dHomeAdapter);
        WaitDialog.show(fgtContext, "数据加载中...");
        page = 1;
        http();
        //刷新

    }


    @NonNull
    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_dhome;
    }

    public static DHomeFragment newInstance() {
        return new DHomeFragment();
    }

    @Override
    public void Success(List<Map<String, String>> data) {
        if (refreshLayout != null) {
            refreshLayout.finishRefresh();
            refreshLayout.finishLoadMore();
        }
        Log.d("refreshLayout", "========page=========" + page);
        if (page == 1) {
            if (data == null || data.size() == 0) {
                frame_gone.setVisibility(View.VISIBLE);
                recycerView.setVisibility(View.GONE);
            } else {
                frame_gone.setVisibility(View.GONE);
                recycerView.setVisibility(View.VISIBLE);
            }
            dHomeAdapter.clear();
            dHomeAdapter.addAll(data);
            text_error.setVisibility(View.GONE);
        } else {
            List<Map<String, String>> allData = dHomeAdapter.getAllData();
            if (allData == null || data == null || allData.size() == 0 || data.size() == 0) {
//                dHomeAdapter.pauseMore();
//                dHomeAdapter.resumeMore();
                text_error.setVisibility(View.VISIBLE);
                return;
            }
            if (allData.get(allData.size() - 1).get("id").equals(data.get(data.size() - 1).get("id"))) {
                return;
            }
            dHomeAdapter.addAll(data);
            text_error.setVisibility(View.GONE);
        }
    }

    @Override
    public void DetaSuccess(Map<String, String> data) {

    }

    @Override
    public void Failed(String msg) {

    }

    @Override
    public void showLoading() {

    }

    @Override
    public void isPay(Map<String, String> data, String type, String do_type) {

    }

    @Override
    public void memberInfor() {
        http();
    }


    public void getCity(String jingdu1, String weidu1, String city, String sex, int type) {
        this.sex = sex;
        this.type = type;
        this.city = city;
        jingdu = jingdu1;
        weidu = weidu1;
        Log.d("getCity", "=====sex===========" + sex);
        Log.d("getCity", "=======type=========" + type);
        Log.d("getCity", "==========city======" + city);
        Log.d("getCity", "========jingdu========" + jingdu);
        Log.d("getCity", "========weidu========" + weidu);
//        WaitDialog.show(fgtContext, "数据加载中...");
        page = 1;
        http();
    }

    public void getCity(String jingdu1, String weidu1, String city, String sex, int type, String aaa) {
        this.sex = sex;
        this.type = type;
        this.city = city;
        jingdu = jingdu1;
        weidu = weidu1;
        Log.d("getCity", "================" + city);
        if (!TextUtils.isEmpty(aaa)) {
            WaitDialog.show(fgtContext, "数据加载中...");
            page = 1;
            http();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(String item) {
        List<Map<String, String>> allData = dHomeAdapter.getAllData();
        if (allData == null) {
            return;
        }
        if (item == null) {
            return;
        }

        Map<String, String> map = allData.get(Integer.valueOf(item));
        String is_like = map.get("is_like");
        if (is_like.equals("1")) {
            dHomeAdapter.getAllData().get(Integer.valueOf(item)).put("is_like", "2");
        } else {
            dHomeAdapter.getAllData().get(Integer.valueOf(item)).put("is_like", "1");
        }
        dHomeAdapter.notifyItemChanged(Integer.valueOf(item));
    }


    private void panduan(Map<String, String> thisdata, int position) {
        //                             是否vip 1否 2是           1未认证 2 已认证
        if (getSex.equals("1")) {
            if (getVip.equals("1")) {
                HttpRequest.POST(fgtContext, "Index/seeCount"
                        , new Parameter()
                                .add("token", token)
                                .add("cover_member_id", thisdata.get("id"))
                        , new ResponseListener() {
                            @Override
                            public void onResponse(String response, Exception error) {
                                if (error != null) {
                                    return;
                                }
                                Map<String, String> map = JSONUtils.parseKeyAndValueToMap(response);
                                if (map.get("code").equals("-1")) {
                                    BaseActivity.alerDialog.show();
                                } else if (map.get("code").equals("1")) {

                                    Map<String, String> data = JSONUtils.parseKeyAndValueToMap(map.get("data"));
                                    if (data.get("look").equals("1")) {
                                        DetailInterfaceActivity.start(fgtContext, thisdata.get("id"), "1", position);
                                        return;
                                    }
                                    int count = Integer.valueOf(data.get("count"));
                                    if (count <= 3 && count > 0) {
                                        //立即开通
                                        MessageDialog.show(fgtContext, "剩余机会" + data.get("count"), "非会员每天只能查看" + data.get("total") + "位女士", "升级会员", "继续查看")
                                                .setOnOkButtonClickListener(new OnDialogButtonClickListener() {
                                                    @Override
                                                    public boolean onClick(BaseDialog baseDialog, View v) {
                                                        Bundle bundle = new Bundle();
                                                        bundle.putString("count", "1");
                                                        bundle.putInt("weixin", 1);
                                                        Intent intent = new Intent(fgtContext, VipActivity.class);
                                                        intent.putExtras(bundle);
                                                        fgtContext.startActivity(intent);
                                                        return false;
                                                    }
                                                })
                                                .setOnCancelButtonClickListener(new OnDialogButtonClickListener() {
                                                    @Override
                                                    public boolean onClick(BaseDialog baseDialog, View v) {
                                                        DetailInterfaceActivity.start(fgtContext, thisdata.get("id"), "1", position);
                                                        return false;
                                                    }
                                                })
                                        ;
                                    } else if (count == 0) {
                                        ToastUtil.show("您没有次数了");
                                    } else {
                                        DetailInterfaceActivity.start(fgtContext, thisdata.get("id"), "1", position);
                                    }

                                } else if (map.get("code").equals("0")) {
                                    ToastUtil.show(map.get("message"));
                                }
                                return;
                            }
                        });
            } else {
                //会员
                DetailInterfaceActivity.start(fgtContext, thisdata.get("id"), "1", position);
                return;
            }
        } else {
            if (getIdentification.equals("1")) {
                HttpRequest.POST(fgtContext, "Index/seeCount"
                        , new Parameter()
                                .add("token", token)
                                .add("cover_member_id", thisdata.get("id"))
                        , new ResponseListener() {
                            @Override
                            public void onResponse(String response, Exception error) {
                                if (error != null) {
                                    return;
                                }
                                Map<String, String> map = JSONUtils.parseKeyAndValueToMap(response);
                                if (map.get("code").equals("-1")) {
                                    BaseActivity.alerDialog.show();
                                    return;
                                } else if (map.get("code").equals("1")) {
                                    Map<String, String> data = JSONUtils.parseKeyAndValueToMap(map.get("data"));
                                    if (data.get("count") == null) {
                                        return;
                                    }
                                    int count = Integer.valueOf(data.get("count"));
                                    if (data.get("look").equals("1")) {
                                        DetailInterfaceActivity.start(fgtContext, thisdata.get("id"), "1", position);
                                        return;
                                    }
                                    if (count <= 3 && count > 0) {
                                        //立即开通
                                        MessageDialog.show(fgtContext, "剩余机会" + data.get("count"), "未认证每天只能查看" + data.get("total") + "位男士", "去认证", "继续查看")
                                                .setOnOkButtonClickListener(new OnDialogButtonClickListener() {
                                                    @Override
                                                    public boolean onClick(BaseDialog baseDialog, View v) {
                                                        //去认证
                                                        Intent intent = new Intent(fgtContext, AuthenticationCenterActivity.class);
                                                        Bundle bundle = new Bundle();
                                                        bundle.putInt("dataSize", 1);
                                                        intent.putExtras(bundle);
                                                        startActivity(intent);
                                                        return false;
                                                    }
                                                })
                                                .setOnCancelButtonClickListener(new OnDialogButtonClickListener() {
                                                    @Override
                                                    public boolean onClick(BaseDialog baseDialog, View v) {
                                                        DetailInterfaceActivity.start(fgtContext, thisdata.get("id"), "1", position);
                                                        return false;
                                                    }
                                                })
                                        ;
                                    } else if (count == 0) {
                                        ToastUtil.show("您没有次数了请先认证");
                                        return;
                                    } else {
                                        DetailInterfaceActivity.start(fgtContext, thisdata.get("id"), "1", position);
                                    }
                                } else {
                                    ToastUtil.show(map.get("message"));
                                }
                                return;
                            }
                        });
            } else {
                DetailInterfaceActivity.start(fgtContext, thisdata.get("id"), "1", position);
            }
        }
    }
}